//
//  SHRefreshControl.swift
//  下拉刷新
//
//  Created by Faner on 16/7/24.
//  Copyright © 2016年 --. All rights reserved.
//

import UIKit

private let RefreshControlH: CGFloat = 50

enum SHRefreshControlState:Int {
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}

private let MyWidth =  UIScreen.mainScreen().bounds.width


class SHRefreshControl: UIControl {
    
    var shState:SHRefreshControlState = .Normal{
        didSet{
            switch shState {
            case .Normal:
//                print("正常")
                messageLabel.text = "正常"
                
                
                if oldValue == .Refreshing {
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= RefreshControlH
                        }, completion: { (_) -> Void in
                            self.pullImageView.hidden = false
                            self.indicatorView.stopAnimating()
                    })
                }
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.pullImageView.transform = CGAffineTransformIdentity
                })
                
                
            case .Pulling:
//                print("下拉中")
                messageLabel.text = "下拉中"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.pullImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    
                })
        
            case .Refreshing:
//                print("刷新中")
                self.pullImageView.hidden = true
                self.indicatorView.startAnimating()
                messageLabel.text = "刷新中"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top += RefreshControlH
                    }, completion: { (_) -> Void in
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                        
                })
            }
        }
    }
    
    var scrollView: UIScrollView?

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -RefreshControlH, width: UIScreen.mainScreen().bounds.width, height: RefreshControlH))
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func endRefreshing(){
        shState = .Normal
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
//        print(newSuperview)
        
        guard let scrollView =  newSuperview as? UIScrollView else{
            return
        }
        
        self.scrollView = scrollView
        
        self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
        
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    
        setupRefreshControllState(self.scrollView?.contentOffset.y)
    }
    
    func setupRefreshControllState(contentOffsetY: CGFloat?) {
        if self.scrollView!.dragging {
            
            
            let contentIntSetTop = self.scrollView?.contentInset.top ?? 0
            
            if contentOffsetY <= -RefreshControlH - contentIntSetTop && shState == .Normal{
                shState = .Pulling
            }else if contentOffsetY > -RefreshControlH - contentIntSetTop && shState == .Pulling{
                shState = .Normal
            }
        }else {
            if shState == .Pulling {
                shState = .Refreshing
            }
        }
        
        
    }
    
    
    private func setupUI(){
        self.backgroundColor = UIColor.brownColor()
        
        addSubview(pullImageView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterY, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
        
        pullImageView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
    }
    
    
    private lazy var messageLabel: UILabel = {
        let lab = UILabel()
       lab.text = "正常"
        lab.textColor = UIColor.whiteColor()
        lab.font = UIFont.systemFontOfSize(15)
        return lab
    }()
    private lazy var indicatorView : UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
       // view.startAnimating()
        return view
    }()
    
    private lazy var pullImageView:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))

}
